<?php

namespace App\Service\Aliyun;

use AlphaSnow\OSS\AppServer\Token;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Ramsey\Uuid\Uuid;

class OssService
{
    public function __construct()
    {

    }

    /**
     * 获取 STS TokenService
     * @param string $dir
     * @param int $expire
     * @return array
     */
    public function sts(string $dir='/', int $expire=3600): array
    {
        $stsToken = app(Token::class);
        $stsToken->policy()->setUserDir($dir)->setExpireTime($expire);
        return $stsToken->response()->toArray();
    }

    /**
     * 上传文件
     * @param UploadedFile $file
     * @param string $basePath
     * @return string
     * @throws Exception
     */
    public function upload(UploadedFile $file, string $basePath=''): string
    {
        try {
            $basePath = '/uploads/'.$basePath.Carbon::now()->format('Ymd');
            $ossPath = Storage::disk("aliyun")->putFile($basePath, $file->path());
            return Storage::url(str_replace('///', '/', $ossPath));
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 本地文件移动到oss
     * @param $file
     * @param $path
     * @param $fileName
     * @return string
     * @throws Exception
     */
    public function moveToOss($file, $path, $fileName): string
    {
        try {
            if (!file_exists($file)) {
                throw new Exception('文件不存在');
            }
            $ossPath = Storage::disk("aliyun")->putFileAs($path, $file, $fileName);
            return str_replace('//', '/', $ossPath);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}
